package chapter14.exercise;

import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import sun.misc.ProxyGenerator;

public class ProxyTest<T> implements InvocationHandler {

    private Object target;
	
	/*public ProxyTest() {
	}*/

    public ProxyTest(Object target) {
        this.target = target;
    }

    @SuppressWarnings("unchecked")
    public T newInstance() {
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    public static Object newInstance(Object target) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new ProxyTest(target));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		/*Object result = null;
		try {
			if(args != null)
				for (Object object : args)
					System.out.println("  " + object);
			result = method.invoke(target, args);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;*/
        System.out.println(proxy.getClass().getName());
        byte[] b = ProxyGenerator.generateProxyClass(proxy.getClass().getSimpleName(), proxy.getClass().getInterfaces());
        FileOutputStream out = new FileOutputStream("./" + proxy.getClass().getSimpleName() + ".class");
        out.write(b);
        out.flush();
        out.close();
        return method.invoke(target, args);
    }

}
